package com.disney.domain.sdk.factory;

import com.disney.domain.sdk.anno.AbsBiz;
import com.disney.domain.sdk.anno.Biz;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 扩展点初始化
 */
@Slf4j
@Component
@SuppressWarnings("all")
public class DomainFactory implements BeanPostProcessor, ApplicationContextAware {

    private static ApplicationContext applicationContext;

    private static final Map<String, Map<Class<? extends IDomainBiz>, List<IDomainBiz>>> extensionMap = Maps.newHashMap();

    /**
     * 取一个扩展点
     *
     * @param request
     * @param clazz
     * @param <E>
     * @return
     */
    public static <E> List<E> getBeans(DomainRequest request, Class<E> clazz) {
        return (List<E>) extensionMap.get(String.format("%s_%s", request.getCode().getCode(), request.getScenario().getCode())).get(clazz);
    }


    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Biz[] annotations = bean.getClass().getAnnotationsByType(Biz.class);
        if (annotations.length == 0) return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);

        Biz biz = annotations[0];
        Class<?> superclass = checkAbs(bean);
        AbsBiz absBiz = superclass.getAnnotation(AbsBiz.class);

        extensionMap.computeIfAbsent(String.format("%s_%s", biz.value().getCode(), absBiz.value().getCode()), v -> Maps.newHashMap())
                .computeIfAbsent((Class<? extends IDomainBiz>) superclass, v -> Lists.newArrayList())
                .add((IDomainBiz) bean);


        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }

    private Class<?> checkAbs(Object bean) {
        Class<?> superclass = bean.getClass().getSuperclass();
        if (Optional.ofNullable(superclass)
                .filter(abs -> !Modifier.isAbstract(abs.getModifiers())
                        || abs.getInterfaces().length != 1
                        || abs.getInterfaces()[0] != IDomainBiz.class)
                .isPresent()) beanSpecs(bean.getClass());

        return superclass;
    }

    private static void beanSpecs(Class<? extends Object> aClass) {
        throw new RuntimeException("根据领域工厂的使用规范，您的编码出现错误，错误如下:bean使用异常 " + aClass);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        DomainFactory.applicationContext = applicationContext;
    }

    public static <T> T getBean(Class<T> clazz) {
        return (T) DomainFactory.applicationContext.getBean(clazz);
    }

    public static Object getBean(String beanName) {
        return DomainFactory.applicationContext.getBean(beanName);
    }

    public static <T> T getBean(String beanName, Class<T> clazz) {
        return (T) DomainFactory.applicationContext.getBean(beanName, clazz);
    }

}
